package com.ds.controller;

import com.ds.dao.DepartmentDao;
import com.ds.dao.EmployeeDao;
import com.ds.entities.Department;
import com.ds.entities.Employee;
import com.sun.org.apache.xpath.internal.operations.Mod;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: SpringBoot
 * @description:
 * @author: Dawson.Zhang
 * @create: 2020-04-19
 **/
@Controller
public class EmpController {
    @Autowired
    EmployeeDao employeeDao;
    @Autowired
    DepartmentDao departmentDao;

    @GetMapping("/emps")
    public String getEmps(Model model) {
        model.addAttribute("emps", employeeDao.getAll());
        System.out.println(employeeDao.getAll());
        return "page/list";
    }

    @GetMapping("/emp")
    public String addEmp(Model model) {
        model.addAttribute("depts", departmentDao.getDepartments());
        return "page/add";
    }

    @PostMapping("/emp")
    public String addEmp(Employee employee) {
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @GetMapping("/emp/{id}")
    public String getEmp(@PathVariable("id") Integer id, Map<String, Object> map) {
        Collection<Department> departments = departmentDao.getDepartments();
        Employee employee = employeeDao.get(id);
        map.put("emp", employee);
        map.put("depts", departments);
        return "page/update";
    }

    @PutMapping("/emp")
    public String updateEmp(Employee employee) {
        System.out.println(employee);
        employeeDao.save(employee);
        return "redirect:/emps";
    }

    @DeleteMapping("/emp/{id}")
    public String deleteEmp(@PathVariable("id") Integer id) {
        employeeDao.delete(id);
        return "redirect:/emps";
    }
}
